﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Frame;
using System.IO;
using System.Threading;

namespace VideoFileOrganization.MoveSubFileUp
{
    public partial class MoveSubFileUp : BaseFrm
    {
        // 在线程中操作 更新界面的委托
        private delegate void IniUiDelegate();
        private string _rootPath;//临时根目录
        public MoveSubFileUp()
        {
            InitializeComponent();
            this.Text = "子文件上调";
            this.Index = 4;
            this.TabImage = Properties.Resources.DocumentCleanup;
            dgSubDir.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }

        protected override void IniUi()
        {
            UpdataSubDir(RootPath);
        }

        private void UpdataSubDir(string rootPath)
        {
            dgSubDir.Rows.Clear();
            if (!Directory.Exists(rootPath)) return;

            // 遍历目录中的所有文件
            foreach (string file in Directory.GetFiles(rootPath))
            {
                dgSubDir.Rows.Add();
                int row = dgSubDir.RowCount - 1;
                dgSubDir.Rows[row].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
                dgSubDir.Rows[row].Cells[0].Value = true;
                dgSubDir.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgSubDir.Rows[row].Cells[1].Value = Path.GetFileName(file);
                dgSubDir.Rows[row].Cells[2].Value = file;
            }

            // 遍历目录中的所有子目录
            foreach (string directory in Directory.GetDirectories(rootPath))
            {
                dgSubDir.Rows.Add();
                int row = dgSubDir.RowCount - 1;
                dgSubDir.Rows[row].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
                dgSubDir.Rows[row].Cells[0].Value = true;
                dgSubDir.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgSubDir.Rows[row].Cells[1].Value = Path.GetFileName(directory);
                dgSubDir.Rows[row].Cells[2].Value = directory;
            }

            //最后一行用于全选
            dgSubDir.Rows.Add();
            int end_row = dgSubDir.RowCount - 1;
            dgSubDir.Rows[end_row].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgSubDir.Rows[end_row].Cells[0].Value = true;
            dgSubDir.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgSubDir.Rows[end_row].Cells[1].Value = "";
            dgSubDir.Rows[end_row].Cells[1].ReadOnly = true;
            dgSubDir.Rows[end_row].Cells[2].Value = "";
            dgSubDir.Rows[end_row].Cells[2].ReadOnly = true;
            dgSubDir.Columns[0].Width = 40;
        }

        protected override void ApplyButton()
        {
            List<string> PathList = new List<string>();
            for (int i = 0; i < dgSubDir.RowCount - 1; i++)
            {
                object cellValue = dgSubDir.Rows[i].Cells[0].Value;
                if (cellValue != null && cellValue.Equals(true))
                {
                    PathList.Add(dgSubDir.Rows[i].Cells[2].Value.ToString());
                }
                else
                {
                    continue;
                }
            }
            if (PathList.Count <= 0) return;

            ParameterizedThreadStart thread = new ParameterizedThreadStart(MoveSubFileUpThread);
            Thread th = new Thread(thread);
            th.Start(PathList);
        }

        private void MoveSubFileUpThread(Object obj)
        {
            Utility.LoadingForm w = new Utility.LoadingForm();
            Thread t = new Thread(() =>
            {
                w.ShowDialog();
            });
            t.Start();
            List<string> PathList = (List<string>)obj;

            foreach(string currentFilePath in PathList)
            {
                // 获取当前文件的父目录路径
                string parentDirectoryPath = Path.GetDirectoryName(currentFilePath);
                string pparentDirectoryPath = Path.GetDirectoryName(parentDirectoryPath);
                // 检查父目录是否存在
                if (Directory.Exists(pparentDirectoryPath))
                {
                    // 移动文件到父目录
                    string newFilePath = Path.Combine(pparentDirectoryPath, Path.GetFileName(currentFilePath));
                    try
                    {
                        if (File.Exists(currentFilePath))
                        {
                            File.Move(currentFilePath, newFilePath);
                        }
                        else
                        {
                            Directory.Move(currentFilePath, newFilePath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("移动文件时发生错误: " + ex.Message);
                    }
                }
                else
                {
                    Console.WriteLine("父目录不存在。");
                }
            }
            string pDirectoryPath = Path.GetDirectoryName(_rootPath);
            DirectoryHelper.DeleteEmptyFolders(pDirectoryPath);
            t.Abort();
            Invoke(new IniUiDelegate(IniUi));
        }

        private void dgSubDir_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            if(dgSubDir.CurrentRow != null && dgSubDir.CurrentRow.Index >= 0)
            {
                DataGridViewRow selectedRow = dgSubDir.CurrentRow;

                _rootPath = selectedRow.Cells[2].Value?.ToString();
                UpdataSubDir(_rootPath);
            }
        }
    }
}
